package com.campus.dao.impl;

import com.campus.dao.UserDao;
import com.campus.model.Role;
import com.campus.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HLQ
 * @date 2024/11/17 23:57
 */
@Slf4j
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    private final RowMapper<User> userRowMapper = new RowMapper<User>() {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User()
                    .setId(rs.getInt("id"))
                    .setLoginName(rs.getString("login_name"))
                    .setPassword(rs.getString("password"))
                    .setGender(rs.getString("gender"))
                    .setBirthday(rs.getDate("birthday"))
                    .setPhone(rs.getString("phone"))
                    .setEmail(rs.getString("email"))
                    .setStatus(rs.getInt("status"));
            return user;
        }
    };

    @Override
    @Transactional
    public int addUser(User user) {
        String sql = "INSERT INTO t_sys_user " +
                "(login_name, password,gender,birthday,phone,email,status) " +
                "VALUES (?,?,?,?,?,?,?)";
        Object[] args = new Object[]{
                user.getLoginName(),
                user.getPassword(),
                user.getGender(),
                user.getBirthday(),
                user.getPhone(),
                user.getEmail(),
                user.getStatus()
        };
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int deleteUserById(int id) {
        String sql = "DELETE FROM t_sys_user WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public int updateUserById(User user) {
        String sql = "UPDATE t_sys_user SET " +
                "(login_name, password,gender,birthday,phone,email,status) " +
                "VALUES (?,?,?,?,?,?,?,?) Where id = ?";
        Object[] args = new Object[]{
                user.getLoginName(),
                user.getPassword(),
                user.getGender(),
                user.getBirthday(),
                user.getPhone(),
                user.getEmail(),
                user.getStatus(),
                user.getId()


        };
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public User queryUserById(int id) {
        String sql = "SELECT * FROM t_sys_user WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, userRowMapper);
    }

    @Override
    public User queryUserByName(String name) {
        String sql = "SELECT * FROM t_sys_user WHERE login_name = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{name}, userRowMapper);
    }


    @Override
    public User selectOne(String name, String password) {
        // 定义SQL查询
        String sql = "SELECT tu.*, tr.id AS role_id, tr.name AS role_name " +
                "FROM t_sys_user tu " +
                "LEFT JOIN t_sys_user_role ur ON tu.id = ur.user_id " +
                "LEFT JOIN t_sys_role tr ON ur.role_id = tr.id " +
                "WHERE tu.login_name = ? AND tu.password = ?";

        // 查询并映射结果
        List<User> users = jdbcTemplate.query(sql, new Object[]{name, password}, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                // 创建 User 对象
                User user = new User()
                        .setId(rs.getInt("id"))
                        .setLoginName(rs.getString("login_name"))
                        .setPassword(rs.getString("password"))
                        .setGender(rs.getString("gender"))
                        .setBirthday(rs.getDate("birthday"))
                        .setPhone(rs.getString("phone"))
                        .setEmail(rs.getString("email"))
                        .setStatus(rs.getInt("status"));

                // 如果角色信息存在，则创建角色对象并添加到角色列表
                user.setRoles(new ArrayList<Role>());
                Role role = Role.builder()
                        .id(rs.getInt("role_id"))
                        .name(rs.getString("role_name"))
                        .build();
                user.getRoles().add(role);  // 添加角色到用户的角色列表

                return user;
            }
        });

        // 如果查询结果为空，则返回 null，否则返回第一个用户
        return users.isEmpty() ? null : users.get(0);
    }

}
